import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:jiang_yue/home/AddCommentInfo.dart';
import 'package:jiang_yue/home/EvaluateShow.dart';
import 'package:jiang_yue/home/StarShow.dart';
import 'package:jiang_yue/home/Toast.dart';
import 'package:jiang_yue/home/UserShow.dart';
import 'package:jiang_yue/modal/Article.dart'; // 文章数据模型
import 'package:jiang_yue/home/CommentShow.dart';
import 'package:jiang_yue/modal/User.dart';
import 'package:jiang_yue/utils/cache/UserCache.dart';
import 'package:jiang_yue/utils/cache/cache.dart';
import 'package:jiang_yue/utils/toast/TsUtils.dart';
import 'package:jiang_yue/home/Evaluate.dart';

class PostShow extends StatefulWidget {
  @override
  int index;
  final callback;
  final int articleID;
  PostShow({
    Key key,
    int this.index, // 索引
    this.callback,
    this.articleID,
  }) : super(key: key);

  _PostShowState createState() => _PostShowState();
}

class _PostShowState extends State<PostShow> {
  bool isEvaluate = false;
  List<int> starList = [0, 0, 0];
  var article;
  var postShow;
  bool isLike;

  // 获取具体的帖子
  void _handlePostShow(int userID, int articleID) async {
    Response response;
    if (userID == null) {
      response = await Dio().get("http://47.93.201.127:8080/jiangyue/postShow", data: {
        "articleID": articleID,
      });
    } else {
      response = await Dio().get("http://47.93.201.127:8080/jiangyue/postShow", data: {
        "userID": userID,
        "articleID": articleID,
      });
    }

    if (response.data['success']) {
      articleShow = response.data['data']['article'];
      commentList = response.data['data']['comment'];
    } else {
      print('报错： PostShow（获取具体帖子）');
    }

    if (article == null ||
        (article['likeNum'] != articleShow['likeNum']) ||
        postShow == null ||
        (postShow['join'] != articleShow['join'])) {
      setState(() {
        article = getArticleTitle(widget.articleID); // 获取父组件中帖子的属性
        postShow = articleShow;
      });
    }
  }

  // 参加活动
  Future _handleJoin(int userID, int articleID) async {
    Response response;
    response = await Dio().post("http://47.93.201.127:8080/jiangyue/join", data: {
      "userID": userID,
      "articleID": articleID,
    });

    if (response.data['success']) {
      TsUtils.showShort('参加成功');
      setState(() {});
    } else {
      Toast.show(context, response.data['msg']); // 如果报错，有两种情况，一是该用户已参加活动，二是该活动人数已满
    }
  }

  // 重新发起请求渲染页面
  handleCallback() {
    setState(() {});
  }

  // 首次进入，先判断isJoin该不该为true
  @override
  void initState() {
    super.initState();
    print(articleInfos);
    isLike = articleInfos[widget.index]['like'];
  }

  @override
  Widget build(BuildContext context) {
    if (userInfo.length == 0) {
      _handlePostShow(null, widget.articleID);
    } else {
      _handlePostShow(userInfo[0].id, widget.articleID);
    }

    print(articleShow);

    // 在点击完评价按钮后该按钮消失
    Widget handleDisplay() {
      if (!isEvaluate) {
        return RaisedButton(
          child: Text('评价'),
          onPressed: () async {
            if (userInfo.length == 0) {
              Toast.show(context, '您未登陆，请登录后重试');
              return;
            }

            Response response;
            response = await Dio().get("http://47.93.201.127:8080/jiangyue/showEvaluateUsers", data: {
              "userID": userInfo[0].id,
              "articleID": widget.articleID,
            });

            if (response.data['success']) {
              evaluateList = response.data['data'];
            } else {
              Toast.show(context, response.data['msg']); // 应是未参加该活动，不能评价
              print('报错： PostShow（获取具体帖子）');
            }

            Navigator.of(context).push(new MaterialPageRoute(
                builder: (context) => new Evaluate(
                      articleID: widget.articleID,
                      userID: userInfo[0].id,
                    )));
          },
          color: Colors.lightBlue[300],
        );
      }
      return Container();
    }

    // 判断活动是否结束
    Widget judgeEnd(String lastTime) {
      int today = DateUtil.getNowDateMs();
      int activityLastTime = int.parse(lastTime);
      if (today > activityLastTime) {
        return Column(
          children: <Widget>[Text('该活动已结束', style: TextStyle(fontSize: 30, color: Colors.grey)), handleDisplay()],
        );
      }

      return Column(
        children: <Widget>[
          Text("已参加：${articleShow['joinNum']} / ${articleShow['limitJoinNum']}"),
          RaisedButton(
            child: Text(postShow['join'] ? '已参加' : '参加'),
            onPressed: () {
              if (userInfo.length == 0) {
                Toast.show(context, '您未登陆，请登录重试');
                return;
              }

              if (articleShow['join']) {
                TsUtils.showShort('您已参加过该活动，请勿重复参加');
                return;
              }

              _handleJoin(userInfo[0].id, widget.articleID);

              handleCallback();
            },
            splashColor: Colors.grey,
            textColor: Theme.of(context).accentColor,
          ),
        ],
      );
    }

    if (article == null) {
      return Scaffold(
        appBar: AppBar(
          title: Text('查找数据'),
        ),
        body: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(letterSpacing: 10, fontSize: 30, color: Colors.grey),
          ),
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('文章详情'),
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        Navigator.of(context).push(new MaterialPageRoute(
                            builder: (context) => UserShow(
                                  userID: articleShow['authorID'],
                                )));
                      },
                      child: Container(
                          height: 50,
                          width: 50,
                          child: CircleAvatar(
                            backgroundImage: AssetImage(articleShow['avatorURL']
                                ),
                            radius: 25,
                          )),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start, // 次轴对齐
                      children: <Widget>[
                        Text(article['author']),
                        Text(articleShow['decoration'], style: TextStyle(color: Colors.grey))
                      ],
                    ),
                  ],
                ),
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: isLike
                          ? Icon(
                              Icons.favorite,
                              color: isLike ? Colors.red : Colors.grey,
                            )
                          : Icon(
                              Icons.favorite_border,
                              color: isLike ? Colors.red : Colors.grey,
                            ),
                      onPressed: () {
                        if (userInfo.length == 0) {
                          Toast.show(context, '您未登陆，请登录重试');
                          return;
                        }

                        widget.callback(userInfo[0].id, widget.articleID, isLike);
                        _handlePostShow(userInfo[0].id, widget.articleID);

                        setState(() {
                          isLike = !isLike;
                        });
                      },
                    ),
                    Text(
                      article['likeNum'].toString(),
                      style: TextStyle(color: isLike ? Colors.red : Colors.grey),
                    ),
                  ],
                )
              ],
            ),
          ),
          EvaluateShow(evaluate: articleShow['evaluate']),
          Padding(
            padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
            child: Text(
              articleShow['content'],
              style: TextStyle(fontSize: 18),
            ),
          ),
          Align(
            alignment: Alignment(0, 1),
            child: judgeEnd(article['lastTime'].toString()),
          ),
          SizedBox(
            height: 16,
          ),
          SizedBox(
            child: Container(
              color: Colors.grey[200],
            ),
            height: 12,
          ),
          Column(
            children: <Widget>[
              AddCommentInfo(
                articleID: widget.articleID,
                callback: handleCallback,
              ), // 增加评论的组件
              CommentShow(
                articleID: widget.articleID,
              ),
            ],
          )
        ],
      ),
    );
  }
}
